from django.contrib.auth.models import User
from django.http import JsonResponse
from rest_framework.generics import GenericAPIView
from rest_framework_simplejwt import authentication
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.exceptions import TokenError
from rest_framework_simplejwt.settings import api_settings
from rest_framework_simplejwt.views import TokenObtainPairView

from common.utils.request import JsonMessage, PageResponse
from common.views import ListModel, AddModel, InfoModel
from user.serializers import UserSerializers, MyTokenObtainPairSerializer


class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer


class UserBase(GenericAPIView, JWTAuthentication):
    queryset = User.objects.all()
    serializer_class = UserSerializers
    Model = User

    def get_object(self):
        try:
            obj = self.Model.objects.get(id=self.request.data['id'])
            return obj
        except Exception as e:
            return e


class UserList(UserBase, ListModel):
    pass


class UserAdd(UserBase, AddModel):
    pass


class UserInfo(UserBase, JWTAuthentication):

    def get_validated_token(self, raw_token):
        for AuthToken in api_settings.AUTH_TOKEN_CLASSES:
            try:
                return AuthToken(raw_token)
            except TokenError as e:
                return JsonMessage(message='accesstoken失效', code=40004).jsonExit()

    def get_user(self, validated_token):
        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            return JsonMessage(message='accesstoken失效', code=40004).jsonExit()

        try:
            user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id})
        except User.DoesNotExist:
            return JsonMessage(message='用户不存在', code=40005).jsonExit()

        if not user.is_active:

            return JsonMessage(message='用户状态非法', code=40006).jsonExit()

        return user


    def post(self, request, *args, **kwargs):
            try:
                if 'accesstoken' in request.headers:
                    accesstoken = request.headers.get('accesstoken')
                    token_msg = self.get_validated_token(accesstoken)
                    user = self.get_user(token_msg)
                    queryset = self.Model.objects.filter(username=user.username)
                    serializer = self.serializer_class(queryset, many=True)
                    return JsonMessage(data=serializer.data[0]).jsonExit()

                else:
                    return JsonMessage(message='accesstoken失效', code=40004).jsonExit()
            except Exception as e:
                return JsonMessage(errors=str(e)).jsonExit()
